package ncu.me.musicplayer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import ncu.me.musicplayer.adapter.MusicAdapter;
import ncu.me.musicplayer.player.MusicManager;
import ncu.me.musicplayer.sql.CollectDao;

public class MusicActivity extends AppCompatActivity {
    Unbinder bind;
    @BindView(R.id.music_list)
    RecyclerView recyclerView;
    @BindView(R.id.music_seek_bar)
    AppCompatSeekBar seekBar;

    @BindView(R.id.btn_play)
    CheckBox btnPlay;

    @BindView(R.id.tvPlayType)
    TextView tvPlayType;

    @BindView(R.id.music_name)
    TextView tvMusicName;
    @BindView(R.id.img_like)
    CheckBox imgLike;
    MusicAdapter adapter;

    SeekListenThread mSeekListenThread;
    private BroadcastReceiver mReceiver;
    private ConnectivityManager.NetworkCallback networkCallback;

    public static void startActivity(Activity activity){
        Intent intent = new Intent();
        intent.setClass(activity,MusicActivity.class);
        activity.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        setTitle("播放列表");
        bind = ButterKnife.bind(this);
        adapter = new MusicAdapter();
        recyclerView.setAdapter(adapter);
        MusicManager manager = MusicManager.getInstance();
        adapter.setList(manager.getList());
        adapter.notifyDataSetChanged();
        //设置歌曲点击事件
        adapter.setOnItemClickListener((v,pos)->{
            MusicManager.getInstance().play(pos);
            btnPlay.setChecked(true);
        });
        seekBar.setMax(manager.size());
        seekBar.setProgress(manager.pos());
        //初始化更新播放进度条线程
        mSeekListenThread = new SeekListenThread(() -> {
            if (seekBar == null){
                return;
            }
            runOnUiThread(() -> {
                if (seekBar==null){
                    return;
                }
                if (manager.size() > 0){
                    seekBar.setMax(manager.size());
                    seekBar.setProgress(manager.pos());
                }

            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //设置进度条拖动的监听
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    manager.seek(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //设置播放按钮状态
        btnPlay.setChecked(manager.isPlaying());

        //加载配置信息
        int lastIndex = getSharedPreferences("setting",MODE_PRIVATE).getInt("index",-1);
        int type = getSharedPreferences("setting",MODE_PRIVATE).getInt("type",MusicManager.LOOP_PLAY);
        MusicManager.getInstance().setIndex(lastIndex);
        MusicManager.getInstance().setPlayType(type);
        adapter.setIndex(lastIndex);
        adapter.notifyDataSetChanged();
        if (type == MusicManager.LOOP_PLAY){
            tvPlayType.setText("循环播放");
        }
        if (type == MusicManager.SINGLE_PLAY){
            tvPlayType.setText("单曲循环");
        }
        if (type == MusicManager.RAND_PLAY){
            tvPlayType.setText("随机播放");
        }
        //注册歌曲播放项改变监听
        MusicManager.getInstance().addIndexChangedListener(this, index -> {
            runOnUiThread(()->{
                btnPlay.setChecked(true);
                adapter.setIndex(index);
                adapter.notifyDataSetChanged();
                if (seekBar!= null){
                    if (MusicManager.getInstance().size()<0){
                        seekBar.setMax(1);
                        seekBar.setProgress(0);
                    }
                    seekBar.setMax(MusicManager.getInstance().size());
                    seekBar.setProgress(MusicManager.getInstance().pos());
                }
                if (tvMusicName != null){
                    tvMusicName.setText(adapter.get(index).getSongName());
                }
                if (imgLike!=null){
                    boolean isLike = CollectDao.getInstance().isHas(adapter.get(index).getId());
                    imgLike.setChecked(isLike);
                }

            });

        });
        //注册播放状态改变监听
        MusicManager.getInstance().addStateChangedListener(this,isPlaying -> {
            btnPlay.setChecked(isPlaying);
        });

        //注册网络状态监听
        networkCallback = new ConnectivityManager.NetworkCallback(){
            @Override
            public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
                super.onCapabilitiesChanged(network, networkCapabilities);
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                    Toast.makeText(getBaseContext(),"wifi网络已连接",Toast.LENGTH_SHORT).show();
                    NetWorkState.setType(NetWorkState.NET_WIFI);
                    return;
                }
                if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
                ||networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
                    Toast.makeText(getBaseContext(),"移动网络已连接",Toast.LENGTH_SHORT).show();
                    NetWorkState.setType(NetWorkState.NET_MOBILE);
                    return;
                }
                Toast.makeText(getBaseContext(),"当前无网络",Toast.LENGTH_SHORT).show();
                NetWorkState.setType(NetWorkState.NET_NULL);
//                boolean b = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
//                if (b){
//                    if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
//                        Toast.makeText(getBaseContext(),"wifi网络已连接",Toast.LENGTH_SHORT).show();
//                        NetWorkState.setType(NetWorkState.NET_WIFI);
//                    }else {
//                        Toast.makeText(getBaseContext(),"移动网络已连接",Toast.LENGTH_SHORT).show();
//                        NetWorkState.setType(NetWorkState.NET_MOBILE);
//                    }
//                }else {
//                    Toast.makeText(getBaseContext(),"当前无网络",Toast.LENGTH_SHORT).show();
//                    NetWorkState.setType(NetWorkState.NET_NULL);
//                }
            }
        };
        //API26+
        ConnectivityManager connectivityManager=getSystemService(ConnectivityManager.class);
        connectivityManager.registerDefaultNetworkCallback(networkCallback);

        //注册播放的前台服务
        Intent intent = new Intent();
        intent.setClass(this,MyService.class);
        startForegroundService(intent);
    }



    //下一首
    @OnClick(R.id.btn_next)
    public void next(){
        MusicManager.getInstance().next();
        if (seekBar!= null){
            seekBar.setProgress(0);
        }
    }
    //上一首
    @OnClick(R.id.btn_previous)
    public void previous(){
        MusicManager.getInstance().previous();
        if (seekBar!= null){
            seekBar.setProgress(0);
        }
    }
    //播放按钮状态发生改变
    @OnCheckedChanged(R.id.btn_play)
    public void play(boolean check){
        if (!check){
            pause();
        }else {
            resume();
        }
    }
    //收藏按钮发生改变
    @OnCheckedChanged(R.id.img_like)
    public void like(boolean check){
        if (check){
            CollectDao.getInstance().insert(adapter.get().getId());
        }else {
            CollectDao.getInstance().deleteByMusicId(adapter.get().getId());
        }
    }
    //暂停
    public void pause(){
        mSeekListenThread.pause();
        MusicManager.getInstance().pause();
    }
    //继续
    public void resume(){
        mSeekListenThread.resume();
        if (MusicManager.getInstance().isStart()){
            MusicManager.getInstance().resume();
        }
        else {
            MusicManager.getInstance().play();
        }
    }
    //列表播放方式改变
    @OnClick(R.id.tvPlayType)
    public void typeChange(View view){
        TextView textView = (TextView) view;
        String text = textView.getText().toString();
        if (text.equals("循环播放")){
            textView.setText("随机播放");
            MusicManager.getInstance().setPlayType(MusicManager.RAND_PLAY);
        }else if (text.equals("随机播放")){
            MusicManager.getInstance().setPlayType(MusicManager.SINGLE_PLAY);
            textView.setText("单曲循环");
        }else {
            textView.setText("循环播放");
            MusicManager.getInstance().setPlayType(MusicManager.LOOP_PLAY);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bind!=null){
            bind.unbind();
            bind = null;
        }
        //取消播放歌曲改变监听
        MusicManager.getInstance().removeIndexChangedListener(this);
        //取消播放状态改变监听
        MusicManager.getInstance().removeStateChangedListener(this);
        //取消网络监听 API26+
        ConnectivityManager connectivityManager=getSystemService(ConnectivityManager.class);
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mSeekListenThread.start();

    }

    @Override
    protected void onStop() {
        super.onStop();
        mSeekListenThread.stop();

    }
    @Override
    protected void onPause() {
        super.onPause();
        //保存配置信息
        getSharedPreferences("setting",MODE_PRIVATE)
                .edit()
                .putInt("index",MusicManager.getInstance().getIndex())
                .putInt("type",MusicManager.getInstance().getPlayType())
                .apply();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //初始化actionbar
        getMenuInflater().inflate(R.menu.atcion_bar,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            //搜索
            case R.id.menu_search:
            {
                SharedPreferences setting = getSharedPreferences("setting", MODE_PRIVATE);
                if (NetWorkState.getType() == NetWorkState.NET_NULL){
                    Toast.makeText(getBaseContext(),"请先连接网络",Toast.LENGTH_SHORT).show();
                    break;
                }
                if (NetWorkState.getType() == NetWorkState.NET_WIFI
                        && !setting.getBoolean("s2",true)){
                    Toast.makeText(getBaseContext(),"当前设置wifi不可用",Toast.LENGTH_SHORT).show();
                    break;
                }
                if (NetWorkState.getType() == NetWorkState.NET_MOBILE
                        && !setting.getBoolean("s1",true)){
                    Toast.makeText(getBaseContext(),"当前设置移动网络不可用",Toast.LENGTH_SHORT).show();
                    break;
                }
                SearchActivity.startActivity(this);
                break;
            }
            //设置
            case R.id.menu_setting:
            {
                View view = getLayoutInflater().inflate(R.layout.setting,null,false);
                AlertDialog alertDialog = new AlertDialog.Builder(this)
                        .setView(view)
                        .create();
                Switch s1 = view.findViewById(R.id.switch1);
                Switch s2 = view.findViewById(R.id.switch2);
                SharedPreferences setting = getSharedPreferences("setting", MODE_PRIVATE);
                s1.setChecked(setting.getBoolean("s1",true));
                s2.setChecked(setting.getBoolean("s2",true));
                s1.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    getSharedPreferences("setting", MODE_PRIVATE)
                            .edit()
                            .putBoolean("s1",isChecked)
                            .apply();
                });
                s2.setOnCheckedChangeListener((buttonView, isChecked) -> {
                    getSharedPreferences("setting", MODE_PRIVATE)
                            .edit()
                            .putBoolean("s2",isChecked)
                            .apply();
                });
                alertDialog.show();
                break;
            }
            //关于
            case R.id.menu_about: {
                StringBuilder msgBuilder = new StringBuilder();
                msgBuilder.append("MusicBox v1.0.0\n");
                msgBuilder.append("作者：\n");
                msgBuilder.append("(C)2019 南昌大学软件学院");
                String title = "关于";
                new AlertDialog.Builder(this)
                        .setIcon(R.drawable.note)
                        .setTitle(title)
                        .setMessage(msgBuilder.toString())
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create().show();
                break;
            }
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
